import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Calculator {
    public static void main(String[] args) {
        JFrame frame = new JFrame("计算器");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);

        CalculatorPanel panel = new CalculatorPanel();
        frame.add(panel, BorderLayout.CENTER);

        frame.setVisible(true);
    }

    public static class CalculatorPanel extends JPanel {
        private JTextField text1;
        private JTextField text2;
        private JTextField resultText;

        public CalculatorPanel() {
            setLayout(new GridLayout(5, 4));

            text1 = new JTextField(20);
            text2 = new JTextField(20);
            resultText = new JTextField(20);
            resultText.setHorizontalAlignment(SwingConstants.RIGHT);

            add(text1);
            add(text2);
            add(new JButton("="));
            add(resultText);

            resultText.setForeground(Color.RED);

            ButtonClickListener listener = new ButtonClickListener(text1, text2, resultText);
            text1.addActionListener(listener);
            text2.addActionListener(listener);
            new JButton("=").addActionListener(listener);
        }

        private class ButtonClickListener implements ActionListener {
            private JTextField text1;
            private JTextField text2;
            private JTextField resultText;

            public ButtonClickListener(JTextField text1, JTextField text2, JTextField resultText) {
                this.text1 = text1;
                this.text2 = text2;
                this.resultText = resultText;
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                String command = e.getActionCommand();

                if (command.charAt(0) == '=') {
                    String expression = text1.getText() + command;
                    try {
                        double result = Double.parseDouble(expression);
                        resultText.setText(String.valueOf(result));
                    } catch (NumberFormatException ex) {
                        resultText.setText("错误");
                    }
                }
            }
        }
    }
}